package com.dims_hsrc.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.dims_hsrc.common.constant.CacheConstants;
import com.dims_hsrc.common.constant.Constants;
import com.dims_hsrc.common.core.domain.AjaxResult;
import com.dims_hsrc.common.core.redis.RedisCache;
import com.dims_hsrc.common.utils.sign.Base64;
import com.dims_hsrc.common.utils.uuid.IdUtils;
import com.dims_hsrc.system.service.ISysConfigService;
import com.dims_hsrc.common.config.DimsHsrcConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 验证码操作处理
 *
 * @author 赵浩然
 */
@RestController
public class CaptchaController {
    private static final Logger log = LoggerFactory.getLogger(CaptchaController.class);

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private DimsHsrcConfig dimsHsrcConfig;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        
        String captchaType = dimsHsrcConfig.getCaptchaType();
        
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        
        if (image == null) {
            log.error("验证码图像生成失败，captchaType: {}, capStr: {}", captchaType, capStr);
            return AjaxResult.error("验证码生成失败");
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(outputImage(image)));
        
        return ajax;
    }

    /**
     * 转换流信息写出
     */
    private byte[] outputImage(BufferedImage image) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
            return os.toByteArray();
        } finally {
            IOUtils.close(os);
        }
    }
}
